import { useData } from '@sker/runtime';
import { HttpError, toSuccess, encryptPassword, generateRandomString, useTransaction, randomSalt } from '@sker/core';
import { z } from 'zod'
import { AutoDevice, AutoUser } from '@sker/entities';
/**
 * 账号及设备登录
 */
export default async () => {
    const input = z.object({
        username: z.string(),
        password: z.string(),
        repassword: z.string()
    });
    const body = input.parse(useData())
    if (body.repassword !== body.password) {
        throw new HttpError(`密码不一致`)
    }
    return await useTransaction(async m => {
        const user = await m.findOne(AutoUser, { where: { username: body.username } })
        if (user) throw new HttpError(`用户已存在`)
        const salt = randomSalt();
        const password = await encryptPassword(body.password, salt)
        const createUser = m.create(AutoUser, {
            username: body.username,
            password: password,
            salt,
            device_count: 0
        })
        await m.save(AutoUser, createUser)
        return toSuccess(true)
    })
}